<template>
  <page-frame>
    <div class="workTyper">
      <div class="toptitle">
        <div class="left">工作计划-排班类型</div>
        <div class="right">
          <div class="btns">
             <el-button class="lightGreenBtn" @click="addSchType">新增班次</el-button>
             <router-link :to="{name:'workPlan'}"><el-button>返回</el-button></router-link>
          </div>
        </div>
      </div>
      <div class="borderT"></div>
      <div class="tabs">
        <el-table
            :data="tableData"
            border
            highlight-current-row
            style="width: 100%">
            <el-table-column
              prop="schTypeName"
              width="300"
              label="班次"
            >
            </el-table-column>
            <el-table-column
              prop="workTimes"
              label="工作时间"
            >
              <template scope="scope">
                <template v-for="n in workTimeLength" v-if="scope.row['timeStart'+n] && scope.row['timeEnd'+n]">
                  {{ n > 1 ? ', ' : '' }}{{ formatTime(scope.row['timeStart'+n]) }}-{{ formatTime(scope.row['timeEnd'+n]) }}
                </template>
              </template>
            </el-table-column>
            <el-table-column
              prop="color"
              label="颜色"
              width="200"
            >
              <template scope="scope">
                <div class="work-typer-table" :style="{backgroundColor:scope.row.color}"></div>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="100"
            >
              <template scope="scope">
                <el-button type="text" size="small" v-show="scope.row.isDel" @click.stop="editSchType(scope.row)">修改</el-button>
                <el-button type="text" size="small" v-show="scope.row.isDel" @click.stop="delSchType(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
      </div>
      <!--新增班次弹框-->
      <el-dialog :title="dialogData.schTypeId ? '编辑班次' : '新增班次'" :visible.sync="showDialog" size="tiny"
                 :close-on-click-modal="false">
        <el-form :model="dialogData" :rules="rules">
          <el-form-item label="班次" prop="schTypeName" :label-width="formLabelWidth">
            <el-col :span="18">
              <el-input v-model="dialogData.schTypeName"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="颜色" prop="color" :label-width="formLabelWidth">
            <el-col :span="18">
              <div class="work-typer-dialog" :style="{backgroundColor:dialogData.color}" ></div>
            </el-col>
            <el-col :span="4" :offset="1" v-if="!readOnly">
              <el-color-picker v-model="dialogData.color" ></el-color-picker>
            </el-col>
          </el-form-item>
          <el-form-item
            v-for="(workTime, index) in dialogData.workTimes"
            :label-width="formLabelWidth"
            :label="'工作时间' + (index + 1)"
            :prop="'workTimes.' + index + '.value'"
          >
            <el-col :span="8">
              <el-time-picker
                v-model="workTime.timeStart"
                placeholder="选择开始时间"
                format="HH:mm">
              </el-time-picker>
            </el-col>
            <el-col :span="1" style="height: 1px;"></el-col>
            <el-col :span="8">
              <el-time-picker
                v-model="workTime.timeEnd"
                placeholder="选择结束时间"
                format="HH:mm">
              </el-time-picker>
            </el-col>
            <el-col :span="4" :offset="1">
              <el-button type="text" @click.prevent="removeTime(index)">删除</el-button>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="4" :offset="1">
              <el-button type="text" @click.prevent="addTime()">增加工作时间段</el-button>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCancel">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </page-frame>
</template>

<script >
  import scheduleApi from '../../service/serManagement/scheduleApi'
  const dialogDefaultData = {
    schTypeId: "",
    schTypeName:'',
    color:'',
    workTimes: [{
      timeStart:"",
      timeEnd:"",
    }]

  };
  export default {
    data () {
      return {
        workTimeLength: 4,
        formLabelWidth:'100px',
        labelPosition: 'right',
        tableData: [],
        showDialog:false,
        dialogData:JSON.parse(JSON.stringify(dialogDefaultData)),
        newWorkTime: "",
        readOnly:false,
        rules: {
        },
      }
    },
    methods: {
      init() {
        this.loadTableData();
      },
      /**
       * 加载数据
       */
      loadTableData(){
        scheduleApi.getScheduleTypeList().then(res => {
          this.tableData = res.body.data;
          for(var data of this.tableData){
            if(data.schTypeName == "休息"){
              data.isDel = false;
            }else {
              data.isDel = true;
            }
          };
          this.handleGetData();
        }, res => {});
      },
      handleGetData() {
        for(let data of this.tableData) {
          for(let i=0; i<this.workTimeLength; i++) {
            let start = data['timeStart' + (i+1)];
            let end = data["timeEnd" + (i+1)];
            if(start && end) {
              data["timeStart" + (i+1)] = new Date(start);
              data["timeEnd" + (i+1)] = new Date(end);
            }
          }
        }
      },
      /**
       * 双击行查看详情
       */
//      handleDbClick(){
//        this.showDialog = true;
//        this.readOnly = true;
//      },
      /**
       * 新增排班类型
       */
      addSchType(){
        this.showDialog = true;
        this.readOnly = false;
      },
      /**
       * 编辑排班类型
       */
      editSchType(row){
        console.log(row);
        this.dialogData = {
          schTypeId: row.schTypeId,
          schTypeName: row.schTypeName,
          color: row.color,
          workTimes: [],
        }
        for(let i=0; i<this.workTimeLength; i++) {
          let timeStart = row['timeStart'+(i+1)];
          let timeEnd = row['timeEnd'+(i+1)];
          if(!timeStart || !timeEnd) {
            break;
          }
          this.dialogData.workTimes.push({timeStart, timeEnd});
        }
        this.showDialog = true;
        this.readOnly = false;
      },
      /**
       * 删除排班类型
       */
      delSchType(row){
        this.$confirm('确定删除该排班类型？', '删除操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          scheduleApi.deleteScheduleType(row.schTypeId).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.init();
          }, res => {})
        }).catch(() => {});
      },
      /**
       * 工作时间是否重叠
       */
      timeOverlap(){
        let submitData = {
          schTypeId: this.dialogData.schTypeId,
          schTypeName: this.dialogData.schTypeName,
          color: this.dialogData.color,
        };
        let startTimeArr = [];
        let endTimeArr = [];
        if(this.dialogData.workTimes.length >= 1){
          for(let i=0; i<this.dialogData.workTimes.length; i++) {
            submitData["timeStart" + (i+1)] = this.dialogData.workTimes[i].timeStart;
            startTimeArr.push(submitData["timeStart" + (i+1)]);
            submitData["timeEnd" + (i+1)] = this.dialogData.workTimes[i].timeEnd;
            endTimeArr.push(submitData["timeEnd" + (i+1)]);
          }
          let begin = startTimeArr.sort();
          let over = endTimeArr.sort();
          if(begin.length >=2){
            for(var k=1;k<begin.length;k++){
              if (begin[k] <= over[k-1]){
                return false;
              }else{
                return submitData;
              }
            };
          }else{
            return submitData;
          };
        }else{
          submitData["timeStart1"] = this.dialogData.workTimes[0].timeStart;
          submitData["timeEnd1"] = this.dialogData.workTimes[0].timeEnd;
          return  submitData;
        };
      },
      /**
       * 弹出框确认
       */
      dialogConfirm() {
        let submitData2 = this.timeOverlap();
        if(!submitData2){
          this.$message({
            type: 'error',
            message: '时间段存在重叠!'
          });
        }else{
          scheduleApi.addOrUpdateScheduleType(submitData2).then(res => {
            this.init();
          }, res => {});
          this.showDialog = false;
          this.newWorkTime = null;
          this.dialogData = JSON.parse(JSON.stringify(dialogDefaultData));
        };
      },
      /**
       * 弹出框取消
       */
      dialogCancel() {
        this.showDialog = false;
        this.newWorkTime = null;
        this.dialogData = JSON.parse(JSON.stringify(dialogDefaultData));
      },
      /**
       * 新增工作时间
       */
      addTime() {
        if(this.dialogData.workTimes && this.dialogData.workTimes.length < 4) {
          this.dialogData.workTimes.push({
            timeStart:"",
            timeEnd:"",
          });
          this.newWorkTime = "";
        }
      },
      /**
       * 删除工作时间
       */
      removeTime(index) {
        this.dialogData.workTimes.splice(index, 1);
      },
      formatTime(date) {
        return window.moment(date).format("HH:mm");
      },
    },

    mounted: function () {
      this.init();
    },
  }
</script>
<style>
  .workTyper .work-typer-table{
    text-align: center;
    line-height: 50px;
    height: 50px;
    width: 100%;
  }
  .workTyper .work-typer-dialog{
    text-align: center;
    line-height: 36px;
    height: 36px;
    width: 100%;
    border-radius:4px;
  }
</style>
